import json
import os
import re

import ModuleUpdate
from utils import to_upper_camel, to_bsp_lower_camel, to_bsp_upper_camel, to_bsp, to_lower_camel, sort_modules, PN

if __name__ == '__main__':
    replaces = [
        [
            {'module': 'SCNS_OV2640', 'keys': ['OV2DEBUG', 'OV2WARNING', 'Ov2640', 'OV2640']},
            {'module': 'SCNS_OV5640', 'keys': ['OV5DEBUG', 'OV5WARNING', 'Ov5640', 'OV5640']},
            {'module': 'SCNS_OV7725', 'keys': ['OV7DEBUG', 'OV7WARNING', 'Ov7725', 'OV7725']},
            {'module': 'SCNS_MT9V034', 'keys': ['MT9DEBUG', 'MT9WARNING', 'Mt9v034', 'MT9V034']},
        ],
        [
            {'module': 'SCNS_CH9141_AT_UART'},
            {'module': 'SCNS_ESP_AT_UART', },
            {'module': 'SCNS_NRF24L01'},
        ],
        [
            {'module': 'SCNS_ICM20602'},
            {'module': 'SCNS_ICM42605'},
            {'module': 'SCNS_MPU6050'},
            {'module': 'SCNS_MPU9250'},
        ],
        [
            {'module': 'SCNS_VL53L1X'},
            {'module': 'SCNS_VL53L0X'},
        ],
        [
            {'module': 'SCNS_ILI9341'},
            {'module': 'SCNS_ILI9481'},
            {'module': 'SCNS_ST7789'},
            {'module': 'SCNS_ST7735'},
            {'module': 'SCNS_ST7796'},
        ],
    ]
    module_names = list(sort_modules(json.loads(open(f'script/{PN}Modules.json', 'r', encoding='gbk', errors='ignore').read().encode("utf-8"))).keys())
    for i in range(0, len(replaces)):
        replaces[i] = sorted(replaces[i], key=lambda x: module_names.index(x['module']))

    for replace in replaces:
        for repl in replace:
            if repl.get('keys') is None:
                repl['keys'] = []
            repl['keys'].append(repl['module'])
            repl['keys'].append(to_upper_camel(repl["module"]))
            repl['keys'].append(to_lower_camel(repl["module"]))
            repl['keys'].append(to_bsp(repl["module"]))
            repl['keys'].append(to_bsp(repl["module"][5:]))
            repl['keys'].append(to_bsp_upper_camel(repl["module"]))
            repl['keys'].append(to_bsp_lower_camel(repl["module"]))
            repl['keys'].append(f'{to_lower_camel(repl["module"][5:8])}N')
    for base in ['./', '../scnsBsp']:
        for root, ds, fs in os.walk(base):
            for f in fs:
                fn = os.path.join(root, f)
                for replace in replaces:
                    for repl in replace:
                        if f'{to_upper_camel(repl["module"])}' in fn or f'{to_bsp_upper_camel(repl["module"])}' in fn:
                            context = context_old = open(fn, 'r', errors='ignore').read()
                            for i, k in enumerate(repl['keys']):
                                for repl2 in replace:
                                    context = context.replace(repl2['keys'][i], repl['keys'][i])
                            similar = ''
                            for repl2 in replace:
                                if repl2['module'] != repl['module']:
                                    similar += f'//@scnsSimilar:{repl2["module"]}\n'
                            context = re.sub(r'(//@scnsSimilar:(.*?)\n)+', similar, context)
                            if context_old != context:
                                with open(fn, 'w', errors='ignore') as f:
                                    f.write(context)

    ModuleUpdate.update()
